import {HeartCheckLoopType, WebsocketService} from "../type";
import {MsgType} from "../constants";

export class HeartCheckLoop implements HeartCheckLoopType{
    // 间隔时间，间隔多久发送一次心跳消息
    interval:number = 15000;
    // 心跳消息超时时间，心跳消息多久没有回复后重连
    timeout:number =  10000;
    timeoutTimer:number =  -1;
    timeoutTimerCheck:number =  -1;
    public constructor(protected socket:WebsocketService) {
    }

    clear() {
        clearTimeout(this.timeoutTimer);
        return this;
    }
    clearAll() {
        this.clear();
        clearTimeout(this.timeoutTimerCheck);
        return this;
    }
    start() {
        this.clear();
        this.socket.sendMessage(MsgType.TYPE_HB, '');
        // 如果超过一定时间还没重置，说明后端主动断开了
        this.timeoutTimer = window.setTimeout(() => {
            this.clearAll();
            this.socket.reconnect();
        }, this.timeout);
        return this;
    }

    // 心跳消息返回
    back() {
        this.clearAll();
        this.timeoutTimerCheck = window.setTimeout(() => this.start(), this.interval);
    }

}
